import axios from 'axios';
import { Toast } from 'vant';
import { baseUrl, token, baseApi } from '@/utils/config/index.js';

axios.defaults.timeout = 60000; // 设置超时
axios.defaults.baseURL = baseUrl;

axios.defaults.headers.post['Content-Type'] = 'multipart/json;charset=UTF-8;';


const service = axios.create({
	baseURL: baseUrl + baseApi, // url = api url + request url
})

//! 请求拦截
service.interceptors.request.use((config) => {
	config.headers.token = token ? token : '';

	// 不传递默认开启loading
	if (!config.hideloading) {
		// loading
		Toast.loading({
			forbidClick: true,
			duration: 0,
			message: config.tips ? config.tips : '加载中'
		})
	}

	return config;
},
	(error) => {
		console.log('err>>>>>>>', error) // for debug
		return Promise.error(error);
	});

//! 响应的拦截
service.interceptors.response.use((response) => {

	// console.log('res>>>>>>>' , response) // for debug

	if (response.status === 200) {
		Toast.clear();

		return Promise.resolve(response.data);
	} else {
		Toast.clear();
		Toast.fail(res.data.msg);

		return Promise.resolve(response.data);
	}
}, (error) => {
	Toast.clear();
	Toast.fail('请求错误');
	console.log('err>>>>>>>', error) // for debug

	return Promise.reject(error)
});

export default service
